package log

import (
	"bufio"
	"fmt"
	"log"
	"os"
)

var loggerFile *log.Logger
var loggerStd *log.Logger
var file *os.File
var writetofile bool
var writer bufio.Writer

func init() {
	loggerStd = log.New(os.Stderr, "", 0)
}

func SetDebug(b bool) {
	if b {
		loggerStd.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
		if writetofile {
			loggerFile.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
		}
	} else {
		loggerStd.SetFlags(0)
		if writetofile {
			loggerFile.SetFlags(0)
		}
	}
}

func WriteToFile(path string) {
	if !writetofile {
		file, _ := os.Create(path)
		writer := bufio.NewWriter(file)
		loggerFile = log.New(writer, "", log.Ldate|log.Lmicroseconds)
		writetofile = true
	}
}

func LogError(args ...interface{}) {
	loggerStd.SetPrefix("[Error] ")
	loggerStd.Output(2, fmt.Sprint(args...))
	if writetofile {
		loggerFile.SetPrefix("[Error] ")
		loggerFile.Output(2, fmt.Sprint(args...))
	}
}

func LogMessage(args ...interface{}) {
	loggerStd.SetPrefix("[Message] ")
	loggerStd.Output(2, fmt.Sprint(args...))
	if writetofile {
		loggerFile.SetPrefix("[Message] ")
		loggerFile.Output(2, fmt.Sprint(args...))
	}
}

func LogWarning(args ...interface{}) {
	loggerStd.SetPrefix("[Warning] ")
	loggerStd.Output(2, fmt.Sprint(args...))
	if writetofile {
		loggerFile.SetPrefix("[Warning] ")
		loggerFile.Output(2, fmt.Sprint(args...))
	}
}

func LogDebug(args ...interface{}) {
	loggerStd.SetPrefix("[Debug] ")
	loggerStd.Output(2, fmt.Sprint(args...))
	if writetofile {
		loggerFile.SetPrefix("[Debug] ")
		loggerFile.Output(2, fmt.Sprint(args...))
	}
}

func TraceInfo(module string, args ...interface{}) {
	flag := loggerStd.Flags()
	loggerStd.SetFlags(0)
	loggerStd.SetPrefix(module + "> ")
	loggerStd.Output(2, fmt.Sprint(args...))
	loggerStd.SetFlags(flag)
}

func CloseLogger() {
	if file != nil {
		writer.Flush()
		file.Close()
		writetofile = false
	}
}
